// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async(event, context) => {

  //通过type判断查看类型
  // 0 - 仅查询下级
  // 1 - 查询本级和下级，并做处理
  if (event.type == '0') {
    return await db.collection('workingGroup').where({
      pid: event.groupId
    }).get().then(res => {
      return res.data
    })
  } else {
    return await db.collection('workingGroup').aggregate().match(db.command.or([{
        pid: event.groupId
      },
      {
        _id: event.groupId
      }
    ])).lookup({
      from: 'address',
      localField: "_id",
      foreignField: "groupId",
      as: "address"
    }).end().then(res => {
      for (var i = 0; i < res.list.length; i++) {
        for (var j = 0; j < res.list[i].address.length; j++) {
          res.list[i].address[j].checked = false
          res.list[i].address[j].color = 'blue'
        }
      }
      return res.list
    })
  }
}